const http = require('http');
const https = require('https');

const API_BASE = 'http://localhost:3000/api';

function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const protocol = url.startsWith('https:') ? https : http;
    
    const requestOptions = {
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    };

    const req = protocol.request(url, requestOptions, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({
            status: res.statusCode,
            data: jsonData
          });
        } catch (e) {
          resolve({
            status: res.statusCode,
            data: data
          });
        }
      });
    });

    req.on('error', (error) => {
      console.error('请求错误:', error.message);
      reject(error);
    });
    
    if (options.body) {
      req.write(options.body);
    }
    
    req.end();
  });
}

async function testSubtaskAPIs() {
  console.log('🧪 开始子任务管理API测试...\n');

  let testTaskId = null;
  let testSubtaskId = null;

  try {
    // 1. 创建一个测试任务
    console.log('1️⃣ 创建测试任务...');
    const createTaskResponse = await makeRequest(`${API_BASE}/tasks`, {
      method: 'POST',
      body: JSON.stringify({
        title: '子任务测试主任务',
        description: '用于测试子任务功能的主任务',
        priority: 'P1',
        category: 'work',
        tags: ['测试'],
        notes: '这是一个测试任务',
        subtasks: [
          { title: '初始子任务1', completed: false },
          { title: '初始子任务2', completed: true }
        ]
      })
    });

    if (createTaskResponse.status === 201) {
      testTaskId = createTaskResponse.data.id;
      console.log(`   ✅ 任务创建成功，ID: ${testTaskId}`);
    } else {
      console.log(`   ❌ 任务创建失败: ${JSON.stringify(createTaskResponse.data)}`);
      return;
    }

    // 2. 获取任务详情（包含子任务）
    console.log('\n2️⃣ 获取任务详情...');
    const getTaskResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`);
    
    if (getTaskResponse.status === 200) {
      console.log(`   ✅ 任务获取成功`);
      console.log(`   📋 任务标题: ${getTaskResponse.data.title}`);
      console.log(`   📝 子任务数量: ${getTaskResponse.data.subtasks.length}`);
      getTaskResponse.data.subtasks.forEach((st, index) => {
        console.log(`      ${index + 1}. ${st.title} [${st.completed ? '✓' : '○'}]`);
      });
    } else {
      console.log(`   ❌ 任务获取失败: ${JSON.stringify(getTaskResponse.data)}`);
    }

    // 3. 获取任务的子任务列表
    console.log('\n3️⃣ 获取子任务列表...');
    const getSubtasksResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}/subtasks`);
    
    if (getSubtasksResponse.status === 200) {
      console.log(`   ✅ 子任务列表获取成功`);
      console.log(`   📝 子任务数量: ${getSubtasksResponse.data.length}`);
      getSubtasksResponse.data.forEach((st, index) => {
        console.log(`      ${index + 1}. [${st.id}] ${st.title} [${st.completed ? '✓' : '○'}]`);
      });
    } else {
      console.log(`   ❌ 子任务列表获取失败: ${JSON.stringify(getSubtasksResponse.data)}`);
    }

    // 4. 添加新子任务
    console.log('\n4️⃣ 添加新子任务...');
    const createSubtaskResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}/subtasks`, {
      method: 'POST',
      body: JSON.stringify({
        title: '动态添加的子任务'
      })
    });

    if (createSubtaskResponse.status === 201) {
      testSubtaskId = createSubtaskResponse.data.id;
      console.log(`   ✅ 子任务创建成功，ID: ${testSubtaskId}`);
      console.log(`   📝 子任务标题: ${createSubtaskResponse.data.title}`);
    } else {
      console.log(`   ❌ 子任务创建失败: ${JSON.stringify(createSubtaskResponse.data)}`);
    }

    // 5. 切换子任务完成状态
    if (testSubtaskId) {
      console.log('\n5️⃣ 切换子任务完成状态...');
      const toggleSubtaskResponse = await makeRequest(`${API_BASE}/tasks/subtasks/${testSubtaskId}/toggle`, {
        method: 'PATCH'
      });

      if (toggleSubtaskResponse.status === 200) {
        console.log(`   ✅ 子任务状态切换成功: ${toggleSubtaskResponse.data.message}`);
      } else {
        console.log(`   ❌ 子任务状态切换失败: ${JSON.stringify(toggleSubtaskResponse.data)}`);
      }
    }

    // 6. 更新子任务标题
    if (testSubtaskId) {
      console.log('\n6️⃣ 更新子任务标题...');
      const updateSubtaskResponse = await makeRequest(`${API_BASE}/tasks/subtasks/${testSubtaskId}`, {
        method: 'PUT',
        body: JSON.stringify({
          title: '已更新的子任务标题',
          completed: true
        })
      });

      if (updateSubtaskResponse.status === 200) {
        console.log(`   ✅ 子任务更新成功: ${updateSubtaskResponse.data.message}`);
      } else {
        console.log(`   ❌ 子任务更新失败: ${JSON.stringify(updateSubtaskResponse.data)}`);
      }
    }

    // 7. 再次获取子任务列表验证更新
    console.log('\n7️⃣ 验证子任务更新...');
    const getUpdatedSubtasksResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}/subtasks`);
    
    if (getUpdatedSubtasksResponse.status === 200) {
      console.log(`   ✅ 更新后的子任务列表:`);
      getUpdatedSubtasksResponse.data.forEach((st, index) => {
        console.log(`      ${index + 1}. [${st.id}] ${st.title} [${st.completed ? '✅' : '⭕'}]`);
      });
    } else {
      console.log(`   ❌ 获取更新后的子任务列表失败: ${JSON.stringify(getUpdatedSubtasksResponse.data)}`);
    }

    // 8. 删除子任务
    if (testSubtaskId) {
      console.log('\n8️⃣ 删除子任务...');
      const deleteSubtaskResponse = await makeRequest(`${API_BASE}/tasks/subtasks/${testSubtaskId}`, {
        method: 'DELETE'
      });

      if (deleteSubtaskResponse.status === 200) {
        console.log(`   ✅ 子任务删除成功: ${deleteSubtaskResponse.data.message}`);
      } else {
        console.log(`   ❌ 子任务删除失败: ${JSON.stringify(deleteSubtaskResponse.data)}`);
      }
    }

    // 9. 最终验证
    console.log('\n9️⃣ 最终验证子任务列表...');
    const finalSubtasksResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}/subtasks`);
    
    if (finalSubtasksResponse.status === 200) {
      console.log(`   ✅ 最终子任务列表:`);
      finalSubtasksResponse.data.forEach((st, index) => {
        console.log(`      ${index + 1}. [${st.id}] ${st.title} [${st.completed ? '✅' : '⭕'}]`);
      });
    } else {
      console.log(`   ❌ 获取最终子任务列表失败: ${JSON.stringify(finalSubtasksResponse.data)}`);
    }

    // 清理：删除测试任务
    if (testTaskId) {
      console.log('\n🧹 清理测试数据...');
      const deleteTaskResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`, {
        method: 'DELETE'
      });

      if (deleteTaskResponse.status === 200) {
        console.log(`   ✅ 测试任务删除成功`);
      } else {
        console.log(`   ❌ 测试任务删除失败: ${JSON.stringify(deleteTaskResponse.data)}`);
      }
    }

  } catch (error) {
    console.error('❌ 测试过程中出现错误:', error);
    console.error('错误详情:', error.message);
    if (error.stack) {
      console.error('错误堆栈:', error.stack);
    }
  }

  console.log('\n🎉 子任务管理API测试完成!');
}

if (require.main === module) {
  testSubtaskAPIs().catch(console.error);
}

module.exports = { testSubtaskAPIs };
